#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "matrixThreeD_utils.h"

// 三维矩阵相加
double*** matrixAdditionTD(int *x, int *y, int *z) {
    int prevX = 0, prevY = 0, prevZ = 0; // 记录前一个矩阵的三个维度大小
    double ***sumMatrix = NULL;
    char continueInput[100];
    // 循环输入
    do {
    	if (!checkTD(x, y, z)) {
	        continue;
	    }
	    // 检查矩阵是否可以相加 
        if (prevX != 0 && (*x != prevX || *y != prevY || *z != prevZ)) {
            printf("矩阵的三个维度大小不匹配，不能相加！\n");
            continue;
        }
        double ***newMatrix = enterMatrixTD(*x, *y, *z);
        if (newMatrix == NULL) {
            if (sumMatrix != NULL) {
                freeMatrixTD(sumMatrix, prevX, prevY, prevZ);
            }
            return NULL;
        }

        if (sumMatrix == NULL) {
            sumMatrix = newMatrix;
            prevX = *x;
            prevY = *y;
            prevZ = *z;
        } else {
            for (int i = 0; i < *x; i++) {
                for (int j = 0; j < *y; j++) {
                    for (int k = 0; k < *z; k++) {
                        sumMatrix[i][j][k] += newMatrix[i][j][k];
                    }
                }
            }
            freeMatrixTD(newMatrix, *x, *y, *z);
        }

        printMatrixTD(sumMatrix, *x, *y, *z);

        printf("如果继续相加请按 y(Y),输入其他值终止,谢谢配合！\n");
        while (getchar() != '\n');
        fgets(continueInput, sizeof(continueInput), stdin);
        continueInput[strcspn(continueInput, "\n")] = 0;
    } while ((continueInput[0] == 'y' || continueInput[0] == 'Y') && continueInput[1] == '\0');

    return sumMatrix;
}

